﻿window.__cnooc_test = false;

var app = angular.module("appModule", ["ngRoute", "ngFileUpload"], function ($httpProvider) {
    $.CNOOCLoading.init();

    // Use x-www-form-urlencoded Content-Type
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';

    /**
     * The workhorse; converts an object to x-www-form-urlencoded serialization.
     * @param {Object} obj
     * @return {String}
     */
    var param = function (obj) {
        var query = '', name, value, fullSubName, subName, subValue, innerObj, i;

        for (name in obj) {
            value = obj[name];

            if (value instanceof Array) {
                for (i = 0; i < value.length; ++i) {
                    subValue = value[i];
                    fullSubName = name + '[' + i + ']';
                    innerObj = {};
                    innerObj[fullSubName] = subValue;
                    query += param(innerObj) + '&';
                }
            }
            else if (value instanceof Object) {
                for (subName in value) {
                    subValue = value[subName];
                    fullSubName = name + '[' + subName + ']';
                    innerObj = {};
                    innerObj[fullSubName] = subValue;
                    query += param(innerObj) + '&';
                }
            }
            else if (value !== undefined && value !== null)
                query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
        }

        return query.length ? query.substr(0, query.length - 1) : query;
    };

    // Override $http service's default transformRequest
    $httpProvider.defaults.transformRequest = [function (data) {
        return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
    }];
});

app.directive('ngChangeOnBlur', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, elm, attrs, ngModelCtrl) {
            if (attrs.type === 'radio' || attrs.type === 'checkbox')
                return;

            var expressionToCall = attrs.ngChangeOnBlur;

            var oldValue = null;
            elm.bind('focus', function () {
                scope.$apply(function () {
                    oldValue = elm.val();
                });
            })
            elm.bind('blur', function () {
                scope.$apply(function () {
                    var newValue = elm.val();
                    if (newValue != oldValue) {
                        scope.$eval(expressionToCall);
                    }
                });
            });
        }
    };
});

app.filter("fixUrl", function () {
    return function (url) {
        if (!url) {
            return url;
        }
        var str = "http://" + url.toString().toLowerCase().replace("http://", "");
        return str;
    }
});

app.config(['$routeProvider', function ($routeProvider) {
    $routeProvider.when("/index", {
        templateUrl: "Ngapp/tpls/index.html",
        controller: "mainController",
        resolve: {
            //permission: function (loginService) {
            //    return loginService.checkLogin();
            //}
            //,
            webServices: function (loginService, daoService, $location) {
                return loginService.checkLogin().then(function (response) {
                    if (response.data.success) {
                        return daoService.loadWebService();
                    } else {
                        $location.path("login");
                    }
                });
            }
        }
    }).when("/wsdlresolve", {
        templateUrl: "Ngapp/tpls/wsdlresolve.html",
        controller: "resolveController",
        resolve: {
            permission: function (loginService, $location) {
                //return loginService.checkLogin();
                return loginService.checkLogin().then(function (response) {
                    if (response.data.success) {
                    } else {
                        $location.path("login");
                    }
                });
            }
        }
    }).when("/postsoap", {
        templateUrl: "Ngapp/tpls/postsoap.html",
        controller: "postsoapController",
        resolve: {
            webServices: function (daoService) {
                return daoService.loadWebService();
            }
        }
    }).when("/login", {
        templateUrl: "NgApp/tpls/login.html",
        controller: "loginController"
    }).otherwise({
        redirectTo: "/postsoap"
    });
}]);

var navController = app.controller("navController", function ($scope, $location, loginService) {
    var path = "#" + $location.path().substr(1);
    if ($location.path() == "") {
        path = "#postsoap"
    }

    $scope.currentNavItem = path;
    $scope.navItems = [{
        name: "SOAP请求", url: "#postsoap"
    }, { name: "服务", url: "#index" }, { name: "WSDL解析", url: "#wsdlresolve" }];
    $scope.switchNav = function (navItem) {
        $scope.currentNavItem = navItem.url;
        //console.log("switchNav",this);
    }

    $scope.loginOut = function () {
        loginService.doLogout().then(function (retData) {
            $location.path("postsoap");
        });
    }
});

var mainController = app.controller("mainController", function (webServices, $scope, $location, Upload,
                                                            commonService, daoService) {
    $scope.webServices = webServices;
    $scope.methods = null;
    $scope.query = "";

    $scope.canEditMethods = false;
    $scope.curWsID = 0;
    $scope.curWebMethodID = 0;
    $scope.dataPacks = null;

    $scope.curEditWebService = null;
    $scope.curWebService = null;
    $scope.attachments = null;

    $scope.refreshWebServices = function () {
        daoService.loadWebService().then(function (retData) {
            $scope.webServices = retData;
        });
    }

    $scope.queryFilter = function (f) {
        //console.log($scope.query);
        if ($scope.query.length > 0) {
            if (parseInt($scope.queryWsID) > 0) {
                if (f.ID == $scope.queryWsID) {
                    return f;
                }
            } else {
                if (f.ServiceName.toLowerCase().indexOf($scope.query.toLowerCase()) >= 0 ||
                    f.ServiceDesc.toLowerCase().indexOf($scope.query.toLowerCase()) >= 0
                    ) {
                    //console.log(f);
                    return f;
                }

            }
        } else {
            return f;
        }
    }

    $scope.delWebService = function (item, index) {
        if (!confirm("是否删除？")) return;
        daoService.delWebService(item.ID).then(function (retData) {
            $scope.webServices.splice(index, 1);
        });
    }

    $scope.changeSort = function (item) {
        daoService.updateWebServiceSort(item.ID, item.Sort).then(function (retData) {
            daoService.loadWebService().then(function (retData) {
                $scope.webServices = retData;
            });
        });
    }

    $scope.changeMethodSort = function (item) {
        daoService.updateMethodSort(item.ID, item.Sort).then(function (retData) {
            daoService.loadMethods($scope.curWsID).then(function (retData) {
                $scope.methods = retData;
                $scope.canEditMethods = true;
            });
        });
    }

    $scope.showMethods = function (ws) {
        //console.log("showMethods->wsID=", ws.ID);
        $scope.query = ws.ServiceName;
        $scope.queryWsID = ws.ID;
        $scope.curWsID = ws.ID;
        daoService.loadMethods(ws.ID).then(function (retData) {
            $scope.methods = retData;
            $scope.canEditMethods = true;
        });
    }

    $scope.backEditMethod = function () {
        $scope.methods = null;
        $scope.canEditMethods = false;
        $scope.query = "";
        $scope.queryWsID = "";
    }

    $scope.showDataPacks = function (m) {
        daoService.loadDataPacks(m.ID).then(function (retData) {
            //console.log("loadDataPacks", retData);
            $scope.dataPacks = retData;
            $scope.curWebMethodID = m.ID;
        });
    }

    $scope.addNewDataPack = function () {
        $scope.dataPacks.push({
            ID: 0,
            WebServiceMethodID: $scope.curWebMethodID,
            SOAPRequestDesc: "",
            DataPack: "",
            Sort: 0,
            DeleteFlag: false
        });
    }

    $scope.saveDataPack = function () {
        var json = JSON.stringify($scope.dataPacks);
        daoService.saveDataPacks(json).then(function (retData) {
            $('#myModal').modal("hide");
        });
    }

    $scope.delDataPack = function (dp, index) {
        daoService.delDataPack(dp.ID).then(function (retData) {
            if (retData.success) {
                $scope.dataPacks.splice(index, 1);
            }
        });
    }


    $scope.editService = function (ws) {
        $scope.curEditWebService = { ServiceDesc: ws.ServiceDesc, WSDLAddress: ws.WSDLAddress, ID: ws.ID, BindingAddress: ws.BindingAddress };
        $scope.curWebService = ws;
    }

    $scope.saveService = function () {
        //console.log($scope.curWebService);
        var json = JSON.stringify($scope.curEditWebService);
        daoService.updateWebService(json).then(function (retData) {
            if (retData.success) {
                $('#editServiceModal').modal("hide");
                $scope.curWebService.ServiceDesc = $scope.curEditWebService.ServiceDesc;
                $scope.curWebService.WSDLAddress = $scope.curEditWebService.WSDLAddress;
                $scope.curWebService.BindingAddress = $scope.curEditWebService.BindingAddress;
                $scope.curEditWebService = null;
            } else {

            }
        });
    }

    $scope.editServiceAttachments = function (ws) {
        $scope.curWebService = ws;
        daoService.loadAttachments(ws.ID).then(function (retData) {
            $scope.attachments = retData;
        });
    }

    $scope.deleteAttachment = function (atta, index) {
        if (confirm("是否删除附件？")) {
            daoService.delAttacment(atta.ID).then(function (retData) {
                if (retData.success) {
                    $scope.attachments.splice(index, 1);
                }
            });
        }
    }

    //上传
    $scope.upload = function (file) {
        $.CNOOCLoading.show();
        Upload.upload({
            url: 'UploadHandler.ashx',
            data: { file: file, 'wsID': $scope.curWebService.ID }
        }).then(function (resp) {
            $.CNOOCLoading.hide();
            //console.log('Success ' + resp.config.data.file.name + 'uploaded. Response: ' + resp.data);
            daoService.loadAttachments($scope.curWebService.ID).then(function (retData) {
                $scope.attachments = retData;
            });
        }, function (resp) {
            //console.log('Error status: ' + resp.status);
            $.CNOOCLoading.hide();
        }, function (evt) {
            var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
            //console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
        });
    };
    // for multiple files:
    $scope.errormsg = "";
    $scope.chnageAttachmentCreatedOn = function (atta) {
        var json = JSON.stringify(atta);
        daoService.updateAttachmentCreatedOn(json).then(function (retData) {
            //console.log(retData);
            if (!retData.success) {
                $scope.errormsg = retData.error;
            } else {
                $scope.errormsg = "";
            }
        });
    }
});

var resolveController = app.controller("resolveController", function ($scope, $location, commonService) {
    $scope.errormsg = "";
    $scope.wsdl = "";
    $scope.wsdlInfo = null;

    //var path = "#" + $location.path().substr(1);
    ////console.log($location.path());
    //console.log("resolveCtrl",path);


    $scope.formatxml = function (type) {
        var data = $scope[type];
        commonService.formatXml(data).then(function (retData) {
            if (retData.success) {
                $scope[type] = retData.xml;
                $scope.errormsg = "";
            } else {
                $scope.errormsg = retData.error;
            }

            $.CNOOCLoading.hide();
        });
    }

    $scope.resolveWsdl = function () {
        commonService.resolveWsdl($scope.wsdl).then(function (retData) {
            if (retData.success) {
                $("#myModal").modal("hide");
                $scope.wsdlInfo = retData.wsInfo;
                $scope.wsdl = "";
                $scope.errormsg = "";
            } else {
                $scope.wsdlInfo = null;
                $scope.errormsg = retData.error;

            }
            $.CNOOCLoading.hide();
        });
    }

    $scope.saveResolvedInfo = function () {
        if (!$scope.wsdlInfo) {
            return;
        }
        if (!$scope.wsdlInfo.Description) {
            alert("请输入服务描述！");
            return;
        }
        var json = JSON.stringify($scope.wsdlInfo);

        commonService.saveWsdlInfo(json).then(function (retData) {
            $.CNOOCLoading.hide();
            $location.path("/index");
        });
    }
});

var postsoapController = app.controller("postsoapController", function (webServices, $scope, $location, commonService, daoService) {
    //webServices.unshift({ ID: 0, ServiceDesc: "请选择--" });
    $scope.webServices = webServices;
    $scope.methods = null;
    $scope.dataPacks = null;
    $scope.wsID = 0;
    $scope.mID = 0;
    $scope.dID = 0;

    $scope.soapData = null;
    $scope.responseData = null;
    $scope.error = "";
    $scope.curWebService = null;

    $scope.attachments = null;
    //console.log(webServices);

    $scope.loadMethods = function () {
        if ($scope.wsID == 0) {
            return;
        }
        angular.forEach($scope.webServices, function (value, key) {
            if (value.ID == $scope.wsID) {
                $scope.curWebService = value;
                //console.log($scope.curWebService);
            }
        });
        daoService.loadMethods($scope.wsID).then(function (retData) {
            retData.unshift({ ID: 0, MethodName: "" });
            $scope.methods = retData;
            $scope.dataPacks = null;
            if (retData && retData.length > 0) {
                //$scope.curMethod = retData[0];
            }

            //$scope.soapData = null;
            //$scope.responseData = null;
            $scope.mID = 0;
            $scope.dID = 0;
            $scope.curDp = null;
            $scope.curMethod = null;
        });

        daoService.loadAttachments($scope.wsID).then(function (retData) {
            $scope.attachments = retData;
        });
        return false;
    }

    $scope.loadDataPacks = function () {
        if ($scope.mID == 0) {
            return;
        }
        daoService.loadDataPacks($scope.mID).then(function (retData) {
            //retData.unshift({ ID: 0, SOAPRequestDesc: "---请选择" });
            $scope.dataPacks = retData;
            //$scope.soapData = null;
            //$scope.responseData = null;
            $scope.dID = 0;
            $scope.curDp = null;
        });
    }

    $scope.setDataPackContent = function () {
        var dataPack = null;
        angular.forEach($scope.dataPacks, function (value, key) {
            if (value.ID == $scope.dID) {
                dataPack = value;
            }
            return false;
        });
        if (dataPack) {
            $scope.soapData = dataPack.DataPack;
        }
    }

    $scope.formatXml = function () {
        if ($scope.soapData) {
            commonService.formatXml($scope.soapData).then(function (retData) {
                if (retData.success) {
                    $scope.soapData = retData.xml;
                    $scope.error = "";
                } else {
                    $scope.error = retData.error;
                }
            });
        }
    }

    $scope.postSoapRequest = function () {
        if ($scope.soapData && $scope.wsID && $scope.mID) {
            commonService.postSoapRequest($scope.soapData, $scope.wsID, $scope.mID)
                .then(function (retData) {
                    //console.log(retData);
                    if (retData.success) {
                        $scope.responseData = retData.xml;
                        $scope.error = "";
                    } else {
                        $scope.error = retData.error;
                        $scope.responseData = "";
                    }
                });
        }
    }

    $scope.curWs = null;
    $scope.curMethod = null;
    $scope.selectWebService = function (ws) {
        $scope.wsID = ws.ID;
        $scope.curWs = ws;
        $scope.loadMethods();
        return false;
    }

    $scope.selectMethod = function (m) {
        $scope.curMethod = m;
        $scope.mID = m.ID;
        $scope.loadDataPacks();
        return false;
    }

    $scope.curDp = null;
    $scope.selectDataPack = function (d) {
        $scope.curDp = d;
        $scope.dID = d.ID;
        $scope.setDataPackContent();
        return false;
    }

    // fitlers
    //$scope.wsQuery = "";
    $scope.wsFilter = function (f) {
        if ($scope.wsQuery) {
            if (f.ServiceName.toLowerCase().indexOf($scope.wsQuery.toLowerCase()) >= 0 ||
                f.ServiceDesc.toLowerCase().indexOf($scope.wsQuery.toLowerCase()) >= 0) {
                return f;
            }
        } else {
            return f;
        }
    }

    $scope.mFilter = function (f) {
        if ($scope.mQuery) {
            if (f.MethodName.toLowerCase().indexOf($scope.mQuery.toLowerCase()) >= 0) {
                return f;
            }
        } else {
            return f;
        }
    }

    $scope.dataPackFilter = function (f) {
        if ($scope.dQuery) {
            if (f.SOAPRequestDesc.toLowerCase().indexOf($scope.dQuery.toLowerCase()) >= 0) {
                return f;
            }
        } else {
            return f;
        }
    }

});

var loginController = app.controller("loginController", function ($scope, $location, loginService) {
    $scope.checkLogin = function (isValid) {
        if (!isValid) {
            alert('请输入用户名或密码！');
            return;
        }
        loginService.doLogin($scope.username, $scope.password).then(function (response) {
            if (response.success) {
                //console.log(lastUrl);
                if (!lastUrl) lastUrl = "index";
                $location.path(lastUrl);
            } else {
                alert("验证失败！");
            }
        });
    }
});

var lastUrl = null;
app.service("loginService", function ($http, $q, $location) {

    return {
        checkLogin: checkLogin,
        doLogin: doLogin,
        doLogout: doLogout,
        lastUrl: $location.path()
    };

    function checkLogin(name) {
        if (__cnooc_test) {
            var defer = $q.defer();
            setTimeout(function () {
                defer.resolve("ok");
            }, 10);
            return defer.promise;
        }
        else {
            lastUrl = $location.path();
            //var q = $http.get("/Ajax.aspx?ajax=true&m=CheckLogin").then(function (response) {
            //    if (response.data.success) {

            //    } else {
            //        $location.path("login");
            //    }
            //}, handleError);
            var q = $http.get("/Ajax.aspx?ajax=true&m=CheckLogin");
            return q;
        }
    }

    function doLogin(username, password) {
        $.CNOOCLoading.show();
        var q = $http.post("/Ajax.aspx?ajax=true&m=DoLogin", { username: username, password: password }).then(handleSuccess, handleError);
        return q;
    }

    function doLogout(username, password) {
        $.CNOOCLoading.show();
        var q = $http.post("/Ajax.aspx?ajax=true&m=DoLogout", { username: username, password: password }).then(handleSuccess, handleError);
        return q;
    }

    function handleError(response) {
        if (
        !angular.isObject(response.data) ||
        !response.data.message
        ) {
            return ($q.reject("An unknown error occurred."));
        }

        // Otherwise, use expected error message.
        $.CNOOCLoading.hide();
        return ($q.reject(response.data.message));

    }

    function handleSuccess(response) {
        $.CNOOCLoading.hide();
        return (response.data);
    }
});

app.service("commonService", function ($http, $q) {
    return {
        formatXml: formatXml,
        resolveWsdl: resolveWsdl,
        saveWsdlInfo: saveWsdlInfo,
        postSoapRequest: postSoapRequest
    };

    function postSoapRequest(soap, wsID, mID) {
        $.CNOOCLoading.show();
        var q = $http.post("/Ajax.aspx?ajax=true&m=PostSOAPRequest&wsID=" + wsID + "&mID=" + mID, { xml: soap }).then(handleSuccess, handleError);
        return q;
    }

    function saveWsdlInfo(info) {
        $.CNOOCLoading.show();
        var q = $http.post("/Ajax.aspx?ajax=true&m=SaveWsdlInfo&t=" + new Date().getTime(), { info: info }).then(handleSuccess, handleError);
        return q;
    }

    function resolveWsdl(wsdl) {
        $.CNOOCLoading.show();
        var q = $http.post("/Ajax.aspx?ajax=true&m=ResolveWsdl&t=" + new Date().getTime(), { xml: wsdl }).then(handleSuccess, handleError);
        return q;
    }

    function formatXml(xml) {
        $.CNOOCLoading.show();
        var q = $http.post("/Ajax.aspx?ajax=true&m=FormatXml&t=" + new Date().getTime(), { xml: xml }).then(handleSuccess, handleError);
        return q;
    }

    function handleError(response) {
        if (
        !angular.isObject(response.data) ||
        !response.data.message
        ) {
            return ($q.reject("An unknown error occurred."));
        }

        // Otherwise, use expected error message.
        $.CNOOCLoading.hide();
        return ($q.reject(response.data.message));

    }

    function handleSuccess(response) {
        $.CNOOCLoading.hide();
        return (response.data);
    }
});

app.service("daoService", function ($http, $q) {
    return {
        loadWebService: loadWebService,
        delWebService: delWebService,
        updateWebService: updateWebService,
        updateWebServiceSort: updateWebServiceSort,
        updateMethodSort: updateMethodSort,
        loadMethods: loadMethods,
        loadDataPacks: loadDataPacks,
        saveDataPacks: saveDataPacks,
        delDataPack: delDataPack,
        loadAttachments: loadAttachments,
        delAttacment: delAttacment,
        updateAttachmentCreatedOn: updateAttachmentCreatedOn
    };

    function updateAttachmentCreatedOn(json) {
        $.CNOOCLoading.show();
        var q = $http.post("/Ajax.aspx?ajax=true&m=UpdateAttachmentCreatedOn", { json: json }).
        then(handleSuccess, handleError);
        return q;
    }

    function delAttacment(attaID) {
        $.CNOOCLoading.show();
        var q = $http.get("/Ajax.aspx?ajax=true&m=DeleteWebServiceAttachment&attaID=" + attaID).then(handleSuccess, handleError);
        return q;
    }

    function loadAttachments(wsID) {
        $.CNOOCLoading.show();
        var q = $http.get("/Ajax.aspx?ajax=true&m=LoadWebServiceAttachments&wsID=" + wsID).then(handleSuccess, handleError);
        return q;
    }

    function loadWebService() {
        $.CNOOCLoading.show();
        var q = $http.get("/Ajax.aspx?ajax=true&m=LoadWebServices&t=" + new Date().getTime()).then(handleSuccess, handleError);
        return q;
    }

    function delWebService(id) {

        $.CNOOCLoading.show();
        var q = $http.get("/Ajax.aspx?ajax=true&m=DeleteWebServices&t=" + new Date().getTime() + "&id=" + id).then(handleSuccess, handleError);
        return q;
    }

    function updateWebService(json) {
        $.CNOOCLoading.show();
        var q = $http.post("/Ajax.aspx?ajax=true&m=UpdateWebService", { json: json }).
        then(handleSuccess, handleError);
        return q;
    }

    function updateWebServiceSort(id, sort) {
        $.CNOOCLoading.show();
        var q = $http.get("/Ajax.aspx?ajax=true&m=UpdateWebServicesSort&t=" + new Date().getTime() + "&id=" + id + "&sort=" + sort).then(handleSuccess, handleError);
        return q;
    }

    function updateMethodSort(id, sort) {
        $.CNOOCLoading.show();
        var q = $http.get("/Ajax.aspx?ajax=true&m=UpdateMethodSort&t=" + new Date().getTime() + "&id=" + id + "&sort=" + sort).then(handleSuccess, handleError);
        return q;
    }

    function loadMethods(id) {
        $.CNOOCLoading.show();
        var q = $http.get("/Ajax.aspx?ajax=true&m=LoadWebServiceMethods&id=" + id).then(handleSuccess, handleError);
        return q;
    }

    function loadDataPacks(id) {
        $.CNOOCLoading.show();
        var q = $http.get("/Ajax.aspx?ajax=true&m=LoadWebServiceMethodDataPakcs&id=" + id).then(handleSuccess, handleError);
        return q;
    }

    function saveDataPacks(json) {
        $.CNOOCLoading.show();
        var q = $http.post("/Ajax.aspx?ajax=true&m=SaveWebServiceMethodDataPakcs", { json: json }).
        then(handleSuccess, handleError);
        return q;
    }

    function delDataPack(id) {
        $.CNOOCLoading.show();
        var q = $http.get("/Ajax.aspx?ajax=true&m=DeleteDataPack&t=" + new Date().getTime() + "&id=" + id).then(handleSuccess, handleError);
        return q;
    }

    function handleError(response) {
        $.CNOOCLoading.hide();
        if (
        !angular.isObject(response.data) ||
        !response.data.message
        ) {
            return ($q.reject("An unknown error occurred."));
        }

        // Otherwise, use expected error message.
        return ($q.reject(response.data.message));

    }

    function handleSuccess(response) {
        $.CNOOCLoading.hide();
        //console.log("handleSuccess",response.data);
        return (response.data);
    }
});

